/**
 * 用户列表
 */
import React from 'react';
import styles from './index.less';
import { connect, history } from 'umi';
import {
  Button,
  Form,
  Input,
  Space,
  Table,
  Switch,
  Modal,
  Tag,
  message,
} from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { Subject } from 'rxjs-compat';
import UserForm from './UserForm';

import commonPkg from '@/utils/commonPkg';
const {
  utils: {
    otherUtil: { authorityVerify },
  },
} = commonPkg;



@connect(({ UserList }) => ({
  UserList,
}))
export default class extends React.Component {
  state = {
    isDelete: false,
  };
  componentDidMount = async () => {
    this.eventInit();
    this.getList();
    this.getAllRoleList();
  };
  eventInit = () => {
    this.searchChangeEvent = new Subject();
    //(防抖)
    this.searchChangeEvent.debounceTime(300).subscribe(data => {
      this.getList({ pageNum: 1, ...data });
    });
  };

  //获得所有角色
  getAllRoleList = async () => {
    var rs = await this.props.dispatch({
      type: 'UserList/getAllRoleList',
    });

    //失败
    if (!rs.success) {
      message.error('删除失败');
    }
    // 成功
    if (rs.success) {
      this.changeState({
        allRoleList: rs.data,
      });
    }
  };

  //获取角色列表
  getRoleList = async (params = {}) => {
    var reqData = {
      pageNum: 1,
      pageSize: 100000000,
      ...params,
    };

    var rs = await this.props.dispatch({
      type: 'UserList/getRoleList',
      payload: reqData,
    });
    // 成功
    if (rs.success) {
      this.changeState({
        roleList: rs.data.dataList,
      });
    }
  };

  // 获取用户列表
  getList = async (params = {}) => {
    const { pageNum, pageSize, searchValue, tabList } = this.props.UserList;
    var reqData = {
      pageNum,
      pageSize,
      val: searchValue,
      ...params,
    };
    // 如果删除的数据为当前页的最后一条
    if (this.state.isDelete && tabList.length == 1 && pageNum > 1) {
      reqData.pageNum -= 1;
      this.state.isDelete = false;
    }
    var rs = await this.props.dispatch({
      type: 'UserList/getUserList',
      payload: reqData,
    });
    // 成功
    if (rs.success) {
      this.changeState({
        tabList: rs.data.dataList,
        total: parseInt(rs.data.total),
        pageSize: parseInt(rs.data.pageSize),
        pageNum: parseInt(rs.data.pageNum),
      });
    }
  };

  //删除用户
  deleteUser = id => {
    Modal.confirm({
      title: '你确定要删除吗?',
      content: '你确定要删除吗?',
      centered: true,
      onOk: async () => {
        // 走接口删除
        var rs = await this.props.dispatch({
          type: 'UserList/deleteUserInfoById',
          payload: { id: id },
        });

        //失败
        if (!rs.success) {
          message.error('删除失败');
        }
        // 成功
        if (rs.success) {
          message.success('删除成功');
          this.setState({ isDelete: true });
          //  更新列表
          this.getList();
        }
      },
    });
  };

  //启用/禁用用户
  getUserEnabled = async (checked, id) => {
    var obj = {
      id: id,
      enabled: checked,
    };
    var rs = await this.props.dispatch({
      type: 'UserList/getUserEnabled',
      payload: obj,
    });

    //失败
    if (!rs.success) {
      message.error('操作失败');
    }
    // 成功
    if (rs.success) {
      message.success('操作成功');
      //  更新列表
      this.getList();
    }
  };

  //更新状态
  changeState = obj => {
    this.props.dispatch({
      type: 'UserList/setState',
      payload: obj,
    });
  };

  // 返回table列表
  renderTableData = (item, i) => {
    var roleVoList = item.roleVoList;
    return {
      key: i,
      1: item.username,
      2: item.name,
      3: roleVoList?.map(item => (
        <Tag  key={item.id} style={{ marginTop: '4px',border:"1px solid #00A0AB",color:"#00A0AB" }}>
          {item.roleName}
        </Tag>
      )),
      4: item.telNum,
      5: item.email,
      6: (
        <Switch
          checked={item.isEnabled}
          onChange={v => {
            if (!authorityVerify('UPDATE_USER')) return;
            this.getUserEnabled(v, item.id);
          }}
        />
      ),
      options: (
        <div>
          <Space size="middle">
            <a
              key={'view'}
              onClick={() => {
                this.changeState({
                  addVisible: true,
                  addVisibleModalType: 'view',
                  addVisibleModalUserId: item.id,
                });
              }}
            >
              查看
            </a>
            <a
              key={'update'}
              onClick={() => {
                if (!authorityVerify('UPDATE_USER')) return;
                this.changeState({
                  addVisible: true,
                  addVisibleModalType: 'update',
                  addVisibleModalUserId: item.id,
                });
              }}
            >
              编辑
            </a>
            <a
              key={'delete'}
              onClick={() => {
                if (!authorityVerify('DEL_USER')) return;
                this.deleteUser(item.id);
              }}
            >
              删除
            </a>
          </Space>
        </div>
      ),
    };
  };

  render() {
    const { tabList, total, pageSize, pageNum } = this.props.UserList;

    const columns = [
      { title: '用户名', width: 100, dataIndex: '1' },
      { title: '姓名', width: 100, dataIndex: '2' },
      { title: '角色分类', width: 200, dataIndex: '3' },
      { title: '手机号', width: 150, dataIndex: '4' },
      { title: '邮箱', width: 150, dataIndex: '5' },
      { title: '状态', width: 100, dataIndex: '6' },
      { title: '操作', width: 150, dataIndex: 'options', fixed: 'right' },
    ];

    return (
      <div className={styles.TableContain}>
        <div className={styles.title}>用户列表</div>
        <div className={styles.FormTable}>
          <Form layout={'inline'}>
            <Form.Item label="选择条件" colon={false}>
              <Input
                allowClear
                placeholder="用户名、姓名和邮箱"
                onChange={e => {
                  this.changeState({ searchValue: e.target.value });
                  this.searchChangeEvent?.next({ val: e.target.value });
                }}
              />
            </Form.Item>
          </Form>
          {/* <Form.Item>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              className={styles.leftBtn}
              onClick={() => {
                if (!authorityVerify('ADD_USER')) return;
                this.changeState({
                  addVisible: true,
                  addVisibleModalType: 'add',
                  addVisibleModalUserId: '',
                });
              }}
            >
              创建用户
            </Button>
          </Form.Item> */}

          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              className={styles.rightBtn}
              onClick={() => {
                // 权限检查  （需要权限时候这里放开）
                // if (!authorityVerify('ADD_USER')) return;
                this.changeState({
                  addVisible: true,
                  addVisibleModalType: 'add',
                  addVisibleModalUserId: '',
                });
              }}
            >
              创建用户
            </Button>
          </div>
        </div>
        <div className={styles.TableList}>
          <div className={styles.total} style={{ left: '10px' }}>
            共{total}条记录 第 {pageNum} /
            {(() => {
              var num = parseInt(total / pageSize);
              if (total % pageSize != 0) num += 1;
              return num;
            })()}{' '}
            页
          </div>

          <Table
            columns={columns}
            dataSource={tabList.map((item, i) => this.renderTableData(item, i))}
            onChange={(pagination, filters, sorter) => {
              this.getList({
                pageNum: pagination.current,
                pageSize: pagination.pageSize,
              });
            }}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              current: pageNum,
              pageSize: pageSize,
              total: total,
              onShowSizeChange: (current, pageSize) => {},
            }}
          />
        </div>

        <UserForm parentThis={this} />
      </div>
    );
  }
}
